import logging
import os
import time


class Logger(object):
    _instance = None  # 确保 logger 只被初始化一次

    def __new__(cls, log_name=None, level=logging.INFO):
        if cls._instance is None:
            cls._instance = super(Logger, cls).__new__(cls)
            cls._instance.init_logger(log_name, level)
        return cls._instance

    def init_logger(self, log_name, level):
        base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
        log_dir = os.path.join(base_dir, "logs")
        if not os.path.exists(log_dir):
            os.mkdir(log_dir)

        if log_name is None:
            timestamp = time.strftime("%Y-%m-%d", time.localtime())
            log_name = f"run_{timestamp}.log"

        log_path = os.path.join(log_dir, log_name)

        self._logger = logging.getLogger("test_logger")
        self._logger.setLevel(level)

        formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S")

        file_handler = logging.FileHandler(log_path, mode="a", encoding="utf-8")
        file_handler.setFormatter(formatter)

        console_handler = logging.StreamHandler()
        console_handler.setFormatter(formatter)

        self._logger.addHandler(file_handler)
        self._logger.addHandler(console_handler)

    def get_logger(self):
        return self._logger
